<?php

declare(strict_types=1);

namespace App\Service;

/**
 * 订单商品
 * Class FlyOrderProductService
 * @package App\Service
 */
class FlyOrderProductService extends BaseService
{

    /**
     * 保存订单商品
     * @param array $product
     * @return bool
     */
    public function saveOrderProduct(array $product): bool
    {
        if (empty($product)) {
            return false;
        }
        $cast = ['order_id', 'sku_id', 'sku_name', 'shop_tag', 'dc_id', 'dc_name', 'limit_quantity', 'landmark', 'product_id',
            'industry_id', 'industry_name', 'is_step_price', 'is_virtual', 'moments_id',
            'product_name', 'single_price', 'quantity', 'subtotal', 'sku_img', 'weight', 'volume', 'tpl_id', 'pay_order_id'];
        foreach ($product as $k => $p) {
            if (empty($p['pay_order_id']) || empty($p['order_id'])) {
                return false;
            }
            foreach ($p as $f => $v) {
                if (!in_array($f, $cast)) {
                    unset($product[$k][$f]);
                }
            }
        }
        $count = 0;
        foreach ($product as $p) {
            $count += $this->getModelInstance()->insert($p);
        }
        return $count == count($product);
    }

    /**
     * 获取获取支付单对应商品
     * @param int $pay_order_id
     * @return array
     */
    public function getProductByPayOrderId(int $pay_order_id): array
    {
        $p = $this->getModelInstance()
            ->where(['pay_order_id' => $pay_order_id])
            ->leftJoin('fly_sku', 'fly_order_product.sku_id', '=', 'fly_sku.sku_id')
            ->select(['fly_order_product.*', 'fly_sku.sku_id as sku_can_use'])
            ->get();
        return empty($p) ? [] : $p->toArray();
    }

}